package com.slf.engine.services.helper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

import com.slf.engine.bo.Order;
import com.slf.engine.bo.WaitBean;
import com.slf.engine.common.SysContants;
import com.slf.engine.common.SysContext;
import com.slf.engine.utils.DateUtils;
import com.slf.engine.utils.KeyedDigestMD5;
import com.zhkj.wsaction.type.TPacket;


public class ServiceHelper {

	private static final Logger log = Logger.getLogger(ServiceHelper.class);
	/**
	 * 补空工具方法
	 * @param s 处理字符串
	 * @param len 字段规定长度
	 * @return 返回处理后的字符串
	 */
	public static String addLeftNull(String s, int len)
	{
		if(s.length() == len)
		{
			return s;
		}
		int i = len - s.length();
		if(i >= 0)
		{
			for(int j = 0; j < i; j++)
			{
				s =" " + s;
			}
		}
		return s;
	}
	
	/**
	 * 补左0工具方法
	 * @param s 处理字符串
	 * @param len 字段规定长度
	 * @return 返回处理后的字符串
	 */
	public static String addLeftZero(String s, int len)
	{	
		if(s.length() == len)
		{
			return s;
		}
		int i = len - s.length();
		if(i >= 0)
		{
			for(int j = 0; j < i; j++)
			{
				s = "0" + s;
			}
		}
		return s;
	}
	
	
	/**
	 * 生成交易头信息
	 * @return
	 */
	public static StringBuffer makeMsg(String body,String type)
	{
		log.log(Priority.INFO, "msgbody：" + body);
		
		StringBuffer header = new StringBuffer();
		header.append(addLeftZero((int)Math.random()*10+"", 10));
		header.append("YDCZ");
		header.append(type);
		
		int len = header.toString().length() + body.toString().length() + 4;
		StringBuffer msg = new StringBuffer();
		msg.append(addLeftZero(len+"", 4));
		msg.append(header.toString());
		msg.append(body);
		return msg;
	}
	
	/**
	 * 生成登录方法体
	 * @return
	 */
	public static StringBuffer makeLoginBody()
	{
		StringBuffer body = new StringBuffer("00000000");
		body.append(SysContants.ZJZH_LOGINNAME);
		body.append(KeyedDigestMD5.getKeyedDigest(SysContants.ZJZH_PASSWORD, ""));
		body.append("0010");
		return body;
	}
	/**
	 * 生成注销方法体
	 * @return
	 */
//	public static StringBuffer makeLogoutBody()
//	{
//		StringBuffer body = new StringBuffer();
//		body.append("0110");
//		body.append(UUID.randomUUID().toString().substring(0, 20));
//		body.append(addLeftZero(SysContants.TJFX_LOGINNAME,8));
//		return body;
//	}
	
	/**
	 * 生成交易方法体
	 * @return
	 */
	public static StringBuffer makeBusBody(Order order)
	{
		StringBuffer body = new StringBuffer();
		body.append(KeyedDigestMD5.getKeyedDigest(SysContants.ZJZH_PAYPWD, ""));
		body.append(addLeftZero(Integer.parseInt(order.getMoney())*100+"", 10));
		body.append(addLeftNull(order.getAccount(), 13));
		body.append(addLeftNull(order.getOrderId(), 20));
		body.append(addLeftNull(SysContants.ZJZH_ZDHM,13));
		body.append(addLeftNull(SysContants.ZJZH_ZDHM,13));
		return body;
	}
	
	public static String[] backMsgHead(String msg)
	{
		if(msg.length() < 28)
		{
			return null;
		}
		String ss[] = new String[5];
		ss[0] = msg.substring(0, 4);
		ss[1] = msg.substring(4, 14);
		ss[2] = msg.substring(14, 18);
		ss[3] = msg.substring(18, 24);
		ss[4] = msg.substring(24, 28);
		return ss;
	}
	
	/**
	 * 放入通知队列
	 */
	public static boolean putToNotice(Order order)
	{
		int i = order.getTzcs();
		order.setTzcs(i++);
		order.setNexttzsj(System.currentTimeMillis() + (long)Math.pow(order.getTzcs(),2));
		SysContext.NOTICE_LIST.add(order);
		return false;
	}
	
	public static Order putPacketToOrder(TPacket packet)
	{
		Order order = new Order();
		order.setOrderId(packet.readFromVarDataAsStr("CZID"));
		order.setAccount(packet.readFromVarDataAsStr("BCZSJH"));
		order.setMoney(Integer.parseInt(packet.readFromVarDataAsStr("CZJE"))/100+"");
		order.setStarttime(DateUtils.strDate("yyyy-MM-dd HH:mm:ss"));
		order.setZdhm(SysContants.ZJZH_ZDHM);
		return order;
	}
	
	/**
	 * 放入查询队列
	 * @param order
	 * @return
	 */
	public static boolean putToCache(Order order)
	{
		log.log(Priority.INFO, "进入查询等待orderId:" + order.getOrderId() + " account:" + order.getAccount() + " money:" + order.getMoney() + " clbz:" + order.getClbz());
		WaitBean waitBean = new WaitBean();
		synchronized (SysContext.QUERY_MAP) {
			if(!SysContext.QUERY_MAP.containsKey(order.getOrderId()))
			{
				waitBean.setOrder(order);
				waitBean.setIsStart(true);
				waitBean.setTimeout(System.currentTimeMillis());
				SysContext.QUERY_MAP.put(order.getOrderId(), waitBean);
				waitBean.start();
				return true;
			}
		}
		return false;
	}
	
	
	/**
	 * 上游失败码返回
	 */
	public static String getErrorMsg(int code)
	{
		Map<Integer, String> map = new HashMap<Integer, String>();
		map.put(3001, "交易失败，系统繁忙");
		map.put(3002, "交易密码不正确");
		map.put(3003, "充值金额必须是5的倍数");
		map.put(3004, "业务已被暂停");
		map.put(3005, "提交的数据格式和内容不正确");
		map.put(3006, "帐户余额不足");
		map.put(3007, "充值面额不正确");
		map.put(3008, "不合法的用户号码");
		map.put(3009, "未开户或者异地手机");
		map.put(3010, "单笔充值金额不能大于500元");
		map.put(3011, "系统清算中，请稍后再试");
		map.put(3012, "重复充值");
		map.put(3013, "移动故障中，请稍后再试");
		map.put(9111, "交易失败");
		map.put(5003, "交易失败");
		
		return map.get(code);
	}
	
	public static List<String> splitRecvMsg(String msg)
	{
		List<String> list = new ArrayList<String>();
		int len = Integer.parseInt(msg.substring(0, 4));
		while(msg.length() >= len)
		{
			list.add(msg.substring(0, len));
			if(msg.length() > len)
			{
				msg = msg.substring(len, msg.length());
				len = Integer.parseInt(msg.substring(0, 4));
			}else{
				return list;
			}
		}
		return list;
	}
	
}
